package th.retrofit.lib;

public class Solution97 {

    private String s1;
    private String s2;
    private String s3;
    private boolean[][] memo;
    public boolean isInterleave1(String s1, String s2, String s3) {
        if (s1.length() + s2.length() != s3.length()) {
            return false;
        }
        memo = new boolean[s1.length() + 1][s2.length() + 1];
        this.s1 = s1;
        this.s2 = s2;
        this.s3 = s3;
        return dfs(0, 0);
    }

    private boolean dfs(int i1, int i2) {
        if (memo[i1][i2]) return false;
        if (i1 == s1.length() && i2 == s2.length()) return true;
        if (i1 < s1.length() && s1.charAt(i1) == s3.charAt(i1 + i2) && dfs(i1 + 1, i2)) {
            return true;
        }
        if (i2 < s2.length() && s2.charAt(i2) == s3.charAt(i1 + i2) && dfs(i1, i2 + 1)) {
            return true;
        }
        memo[i1][i2] = true;
        return false;
    }

    public boolean isInterleave(String s1, String s2, String s3) {
        int len1 = s1.length();
        int len2 = s2.length();
        int len3 = s3.length();
        if (len1 + len2 != len3) return false;
        boolean[][] dp = new boolean[len1 + 1][len2 + 1];
        for (int i = 0; i <= len1; i++) {
            for (int j = 0; j <= len2; j++) {
                if (i == 0 && j == 0) {
                    dp[i][j] = true;
                } else if (i == 0 && j > 0){
                    dp[i][j] = dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);
                } else if (i > 0 && j == 0){
                    dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i - 1);
                } else {
                    dp[i][j] = (s1.charAt(i - 1) == s3.charAt(i + j - 1) && dp[i - 1][j])
                            || (s2.charAt(j - 1) == s3.charAt(i + j - 1) && dp[i][j - 1]);
                }
            }
        }
        return dp[len1][len2];
    }

    public static void main(String[] args) {
        System.out.println(new Solution97().isInterleave1("aabcc", "dbbca", "aadbbcbcac"));
    }

}
